package pox.channel;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class SharedStringChannel {
	// 单元格值缓冲队列
	private static BlockingQueue<StringBuffer> blockingQueue = new LinkedBlockingQueue<StringBuffer>();
	// 当前值坐标
	private static Long index = new Long(-1);
	private static String START = "<si><t>";
	private static String END = "</t></si>";

	public static Long addSharedString(String sharedString) {
//		System.out.println(sharedString);
		// 拼接标签
		StringBuffer sb = new StringBuffer(START);
		sb.append(sharedString);
		sb.append(END);
		blockingQueue.add(sb);
		// 脚标递增
		index += 1;
		return index;
	}

	// 清理管道
	public static void clean() {
		index = new Long(-1);
		blockingQueue.clear();
	}

	/**
	 * 获取管道内容 , 如果当前队列中没有数据则等待一秒,在1秒时间内获取到则正常返回..超出时间返回null
	 * 
	 * @return
	 */
	public static String getSharedString() {
		try {
			StringBuffer sharedString = blockingQueue.poll(1, TimeUnit.SECONDS);
			if (null == sharedString) {
				System.out.println(sharedString);
				return null;
			}
			return sharedString.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// public static String getBigSharedString() {
	// StringBuffer buffer = new StringBuffer();
	// String str;
	// for (int i = 0; i < 10; i++) {
	// str = getSharedString();
	// if (str == null) {
	// break;
	// }
	// buffer.append(str);
	// }
	// if (buffer.toString().equals("")) {
	// return null;
	// }
	// return buffer.toString();
	//
	// }
	/**
	 * 获取当前脚标位置
	 * 
	 * @return
	 */
	public static Long getIndex() {
		return index;
	}

}
